package com.yupfeg.executor.ext

import com.yupfeg.executor.ExecutorFactory
import com.yupfeg.executor.ExecutorProvider
import com.yupfeg.executor.ThreadPoolBuilder
import java.util.concurrent.ExecutorService

/**
 * 准备全局线程池配置
 * - 如不需要修改线程池配置，无需调用该函数
 * @param init 初始化线程池工厂类的高阶函数
 * */
fun prepareExecutor(init : ()->ExecutorFactory){
    ExecutorProvider.prepare(init())
}

// <editor-fold desc="线程池工厂拓展">

/**
 * 构建默认CPU配置的线程池工厂
 * - CPU密集型线程池保持默认配置，只有固定核心线程的有界有队列线程池，
 * 无界缓冲队列（Integer.MAX_VALUE），会在无空闲线程时缓存任务
 * @param ioPoolConfig kotlin-dsl方式配置io密集型线程池
 * */
@Suppress("unused")
fun buildDefCPUThreadPoolFactory(
    ioPoolConfig : ThreadPoolBuilder.()->Unit
) : ExecutorFactory{
    return object : ExecutorFactory{
        override fun createIOThreadPool(): ExecutorService {
            return ioThreadPoolBuilder(ioPoolConfig).build()
        }

        override fun createCPUThreadPool(): ExecutorService {
            return cpuThreadPoolBuilder{}.build()
        }
    }
}

/**
 * 构建默认IO配置的线程池工厂
 * - IO密集型线程池保持默认配置，无核心线程的无界无队列线程池，没有缓冲队列，有任务就会直接给线程执行
 * @param cpuPoolConfig kotlin-dsl方式配置cpu密集型线程池
 * */
@Suppress("unused")
fun buildDefIOThreadPoolFactory(
    cpuPoolConfig : ThreadPoolBuilder.()->Unit
) : ExecutorFactory{
    return object : ExecutorFactory{
        override fun createIOThreadPool(): ExecutorService {
            return ioThreadPoolBuilder{}.build()
        }

        override fun createCPUThreadPool(): ExecutorService {
            return cpuThreadPoolBuilder(cpuPoolConfig).build()
        }
    }
}

// </editor-fold>

// <editor-fold desc="配置线程池">

/**
 * 创建线程池配置构建类
 * @param init kotlin-dsl方式配置线程池
 * */
@Suppress("unused")
fun threadPoolBuilder(init : ThreadPoolBuilder.()->Unit) : ThreadPoolBuilder{
    return ThreadPoolBuilder().apply(init)
}

/**
 * 创建IO密集型线程池配置构建类
 * @param init kotlin-dsl方式配置io密集型线程池
 * */
@Suppress("unused")
fun ioThreadPoolBuilder(init: ThreadPoolBuilder.()->Unit) : ThreadPoolBuilder{
    return ThreadPoolBuilder.createDefaultIOBuilder().apply(init)
}

/**
 * 创建CPU密集型线程池配置构建类
 * @param init kotlin-dsl方式配置cpu密集型线程池
 * */
@Suppress("unused")
fun cpuThreadPoolBuilder(init: ThreadPoolBuilder.() -> Unit) : ThreadPoolBuilder{
    return ThreadPoolBuilder.createDefaultCpuBuilder().apply(init)
}

// </editor-fold>